package com.equipmentRent.web.controller.system;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import com.equipmentRent.common.utils.ShiroUtils;
import com.equipmentRent.system.domain.Item;
import com.equipmentRent.system.domain.Order;
import com.equipmentRent.system.domain.OrderDetail;
import com.equipmentRent.system.domain.VO.LeaseRecordVo;
import com.equipmentRent.system.domain.VO.OrderDetailsVo;
import com.equipmentRent.system.domain.dto.LeaseRecordIdDto;
import com.equipmentRent.system.service.IItemService;
import com.equipmentRent.system.service.IOrderDetailService;
import com.equipmentRent.system.service.IOrderService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.equipmentRent.common.annotation.Log;
import com.equipmentRent.common.enums.BusinessType;
import com.equipmentRent.system.domain.LeaseRecord;
import com.equipmentRent.system.service.ILeaseRecordService;
import com.equipmentRent.common.core.controller.BaseController;
import com.equipmentRent.common.core.domain.AjaxResult;
import com.equipmentRent.common.utils.poi.ExcelUtil;
import com.equipmentRent.common.core.page.TableDataInfo;

import javax.annotation.Resource;

/**
 * 租赁出库记录Controller
 * 
 * @author ruoyi
 * @date 2025-05-28
 */
@Controller
@RequestMapping("/system/lease")
public class LeaseRecordController extends BaseController
{
    private String prefix = "system/lease";

    @Autowired
    private ILeaseRecordService leaseRecordService;

    @Resource
    private IOrderService orderService;

    @Resource
    private IOrderDetailService orderDetailService;

    @Resource
    private IItemService iItemService;

    @RequiresPermissions("system:lease:view")
    @GetMapping()
    public String lease(ModelMap mmap)
    {
        mmap.put("itemList", iItemService.selectItemList(new Item()));
        return prefix + "/lease";
    }

    /**
     * 查询租赁出库记录列表
     */
    @RequiresPermissions("system:lease:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(LeaseRecord leaseRecord)
    {
        startPage();
        List<LeaseRecordVo> list = leaseRecordService.selectLeaseRecordVoList(leaseRecord);
        return getDataTable(list);
    }

    /**
     * 导出租赁出库记录列表
     */
    @RequiresPermissions("system:lease:export")
    @Log(title = "租赁出库记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(LeaseRecord leaseRecord)
    {
        List<LeaseRecord> list = leaseRecordService.selectLeaseRecordList(leaseRecord);
        ExcelUtil<LeaseRecord> util = new ExcelUtil<LeaseRecord>(LeaseRecord.class);
        return util.exportExcel(list, "租赁出库记录数据");
    }

    /**
     * 新增租赁出库记录
     */
    @GetMapping("/add")
    public String add(ModelMap mmap)
    {
        mmap.put("itemList", iItemService.selectItemList(new Item()));
        mmap.put("orderList", orderService.selectOrderList(new Order()));
        return prefix + "/add";
    }

    /**
     * 新增保存租赁出库记录
     */
    @RequiresPermissions("system:lease:add")
    @Log(title = "租赁出库记录", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    @Transactional
    public AjaxResult addSave(LeaseRecord leaseRecord)
    {
//        修改订单状态
        Order order = orderService.selectOrderById(leaseRecord.getOrderId());
        OrderDetail orderDetail = orderDetailService.selectOrderDetailByOrderIdAndItemId(order.getId(), leaseRecord.getItemId());
        orderDetail.setStatus(2L);
//        修改单条子项出库状态
        orderDetailService.updateOrderDetail(orderDetail);
//        判断主表订单是 部分尚未去除还是 待归还
        List<OrderDetail> orderDetailList = orderDetailService.selectOrderDetailByOrderIdAndStatus(order.getId(), 1L);
//        如果子表都取完了，则修改订单状态为待归还
        if (CollectionUtils.isEmpty(orderDetailList)){
            order.setStatus(1);
        }
        orderService.updateOrder(order);

        String userName = ShiroUtils.getSysUser().getUserName();
        leaseRecord.setOperator(userName);
        return toAjax(leaseRecordService.insertLeaseRecord(leaseRecord));
    }

    /**
     * 查询租赁出库包含的出库项目
     * @param leaseRecordIdDto
     * @return
     */
    @PostMapping("/queryLeaseRecordItems")
    @ResponseBody
    public AjaxResult queryLeaseRecordItems(@RequestBody LeaseRecordIdDto leaseRecordIdDto){
        String leaseRecordId = leaseRecordIdDto.getLeaseRecordId();
        LeaseRecord leaseRecord = leaseRecordService.selectLeaseRecordById(Long.valueOf(leaseRecordId));
        List<OrderDetail> orderDetails = orderDetailService.selectOrderDetailByOrderId(leaseRecord.getOrderId());
        List<OrderDetailsVo> orderDetailsVos = new ArrayList<>();
        orderDetails.forEach(orderDetail -> {
            Item item = iItemService.selectItemById(orderDetail.getItemId());
            orderDetailsVos.add(OrderDetailsVo.builder()
                    .orderId(orderDetail.getOrderId())
                    .itemName(Optional.ofNullable(item).map(Item::getName).orElse("--"))
                    .imgUrl(Optional.ofNullable(item).map(Item::getImgUrl).orElse("--"))
                    .quantity(leaseRecord.getLeaseQuantity().toString())
                    .dailyRate(orderDetail.getDailyRate().toString())
                    .days(orderDetail.getDays().toString())
                    .itemId(item.getId().toString())
                    .status(orderDetail.getStatus().intValue())
                    .build());
        });
        return AjaxResult.success(orderDetailsVos);
    }

    /**
     * 修改租赁出库记录
     */
    @RequiresPermissions("system:lease:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        LeaseRecord leaseRecord = leaseRecordService.selectLeaseRecordById(id);
        mmap.put("itemList", iItemService.selectItemList(new Item()));
        mmap.put("orderList", orderService.selectOrderList(new Order()));
        mmap.put("leaseRecord", leaseRecord);
        return prefix + "/edit";
    }

    /**
     * 修改保存租赁出库记录
     */
    @RequiresPermissions("system:lease:edit")
    @Log(title = "租赁出库记录", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(LeaseRecord leaseRecord)
    {
        String userName = ShiroUtils.getSysUser().getUserName();
        leaseRecord.setOperator(userName);
        return toAjax(leaseRecordService.updateLeaseRecord(leaseRecord));
    }

    /**
     * 删除租赁出库记录
     */
    @RequiresPermissions("system:lease:remove")
    @Log(title = "租赁出库记录", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(leaseRecordService.softDeleteLeaseRecordByIds(ids));
    }
}
